import { Pass } from './Pass'
class BlurStage2 extends Pass {
  constructor (options) {
    super(options.scene)
    const texSize = options.texSize
    const direction = options.direction
    const colorTexture = options.colorTexture
    const kernelRadius = options.kernelRadius

    const uniforms = {
      texSize,
      direction
    }
    if (GC.defined(colorTexture)) {
      uniforms.colorTexture = colorTexture
    }

    this.name = 'czm_blurPass2_' + GC.createGuid()

    this.stage = new GC.PostProcessStage({
      name: this.name,
      fragmentShader: this.fragmentShader(kernelRadius, colorTexture),
      uniforms,
      sampleMode: GC.PostProcessStageSampleMode.LINEAR
    })
  }

  fragmentShader (kernelRadius) {
    return `
      #define KERNEL_RADIUS ${kernelRadius}
      #define SIGMA ${kernelRadius}
      uniform sampler2D colorTexture;
      uniform vec2 texSize;
      uniform vec2 direction;
      in vec2 v_textureCoordinates;
      float gaussianPdf(in float x, in float sigma){
        return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;
      }
      void main() {
        // vec2 invSize = czm_pixelRatio / czm_viewport.zw;
        vec2 invSize = (1.0 / texSize);
        float fSigma = float(SIGMA);
        float weightSum = gaussianPdf(0.0, fSigma);
        vec3 diffuseSum = texture( colorTexture, v_textureCoordinates).rgb * weightSum;
        for( int i = 1; i < KERNEL_RADIUS; i ++ ) {
          float x = float(i) * 0.03;
          float w = gaussianPdf(x, fSigma);
          vec2 uvOffset = direction * invSize * x;
          vec3 sample1 = texture( colorTexture, v_textureCoordinates + uvOffset).rgb;
          vec3 sample2 = texture( colorTexture, v_textureCoordinates - uvOffset).rgb;
          diffuseSum += (sample1 + sample2) * w;
          weightSum += 2.0 * w;
        }
        out_FragColor = vec4(diffuseSum/weightSum, 1.0);
      }
    `
  }
}

export default BlurStage2
